package com.huang.controller;

import com.huang.pojo.Role;
import com.huang.pojo.User;
import com.huang.service.LoginService;
import com.huang.service.RoleService;
import com.huang.service.UserService;
import com.huang.vo.PageResult;
import com.huang.vo.Result;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Resource
    private UserService userService;
    @Resource
    private RoleService roleService;
    @Resource
    private LoginService loginService;

    @RequestMapping(value = "/user/login",method = RequestMethod.POST)
    @ResponseBody
    public Result login(User user, HttpServletRequest request){
        User loginUserInfo = loginService.loginByUserNameAndPassD(user);
        Result result;
        if (loginUserInfo == null) {
            // 登录失败
            result = new Result(200,"error","登录失败，账号或者密码错误",null);
        } else {
            // 判断 用户和用户的角色是否有效
            Role role = roleService.findById(loginUserInfo.getR_id());
            if (role.getR_state() == 0 && loginUserInfo.getU_state() == 0){
                // 登录成功
                HttpSession session = request.getSession();
                session.setAttribute("userInfo",loginUserInfo);
                result = new Result(200,"success","登录成功",loginUserInfo);
            } else{
                result = new Result(403,"error","登录被限制",null);
            }
        }
        return result;
    }


    @RequestMapping(value = "/user/logout", method = RequestMethod.GET)
    @ResponseBody
    public Result logOut(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.invalidate();
        return new Result(200,"success","退出成功",null);
    }
    @RequestMapping(value = "/user/getInfo", method = RequestMethod.GET)
    @ResponseBody
    public Result getUserInfo(HttpServletRequest request){
        HttpSession session = request.getSession();
        User userInfo = (User) session.getAttribute("userInfo");
        // session没有值 返回错误信息
        if (userInfo == null) return new Result(200,"fail","获取失败",null);
        Role role = roleService.findById(userInfo.getR_id());
        userInfo.setRole(role);
        return new Result(200,"success","获取成功",userInfo);
    }

}
